var express = require('express');
var router = express.Router();
var { userModel,identityModel } = require('../../../model/model');
/* GET home page. */


// -------------------------------账号管理--------------------------------------
// 获取账号信息
router.get('/getuser', async (req, res) => {
  let item = req.query.data
  if (item != undefined) {
    let Real_name = RegExp(item.item)
    let data = await userModel.find({ Real_name: Real_name }).populate('cid')
    console.log(data);
    res.send({
      code: 200,
      data: data
    })
  } else {
    let data = await userModel.find().populate('cid')
    data.forEach(item=>{
      item.cos=item.cid.identity_name
    })
    res.send({
      code: 200,
      data: data
    })
  }
})

// 添加账号信息
router.post('/adduser', async (req, res) => {
  let data = req.body.data.from
  console.log(data);
  if (data != '') {
    await userModel.create(data)
    res.send({
      code: 200,
      msg: '添加成功'
    })
  }
})

// 删除账号信息
router.get('/deluser', async (req, res) => {
  let _id = req.query.data.list_id
  console.log(_id);
  // 批量删除一次性
  await userModel.deleteMany({ _id: { $in: _id } })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})

//获取要修改的数据
router.get('/edituser', async (req, res) => {
  let _id = req.query.data.list_id
  let data = await userModel.find({ _id: { $in: _id } })
  res.send({
    code: 200,
    data: data
  })
})

// 修改账号信息
router.post('/updateuser', async (req, res) => {
  let data = req.body.data.from

  await userModel.updateOne({ _id: data._id }, data)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})


// ------------------------------角色管理-----------------------------------
// 获取角色信息
router.get('/getcos', async (req, res) => {
  let user = req.query.data
  if (user != undefined) {
    let identity_name = RegExp(user.item)
    let data = await identityModel.find({ identity_name: identity_name })
    res.send({
      code: 200,
      data: data
    })
  } else {
    let data = await identityModel.find()
    res.send({
      code: 200,
      data: data
    })
  }
})

// 添加角色
router.post('/addcos', async (req, res) => {
  let data = req.body.data.from
  await identityModel.create(data)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 删除账号信息
router.get('/delcos', async (req, res) => {
  let _id = req.query.data.list_id
  console.log(_id);
  // 批量删除一次性
  await identityModel.deleteMany({ _id: { $in: _id } })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})

//获取要修改的数据
router.get('/coseditcos', async (req, res) => {
  let _id = req.query.data._id
  let data = await identityModel.find({ _id: { $in: _id } })
  res.send({
    code: 200,
    data: data
  })
})

// 修改账号信息
router.post('/cosupdatecos', async (req, res) => {
  let data = req.body.data.from
  console.log(data);
  await identityModel.updateOne({ _id: data._id }, data)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})





module.exports = router;
